// DOM元素
const loginForm = document.getElementById('loginForm');
const registerForm = document.getElementById('registerForm');
const loginUsername = document.getElementById('loginUsername');
const loginPassword = document.getElementById('loginPassword');
const loginUsernameError = document.getElementById('loginUsernameError');
const loginPasswordError = document.getElementById('loginPasswordError');
const registerUsername = document.getElementById('registerUsername');
const registerEmail = document.getElementById('registerEmail');
const registerPassword = document.getElementById('registerPassword');
const registerConfirmPassword = document.getElementById('registerConfirmPassword');
const registerUsernameError = document.getElementById('registerUsernameError');
const registerEmailError = document.getElementById('registerEmailError');
const registerPasswordError = document.getElementById('registerPasswordError');
const registerConfirmPasswordError = document.getElementById('registerConfirmPasswordError');
const agreeTerms = document.getElementById('agreeTerms');
const agreeTermsError = document.getElementById('agreeTermsError');
const toggleLoginPassword = document.getElementById('toggleLoginPassword');
const toggleRegisterPassword = document.getElementById('toggleRegisterPassword');
const toggleRegisterConfirmPassword = document.getElementById('toggleRegisterConfirmPassword');
const commentForm = document.getElementById('commentForm');
const commentContent = document.getElementById('commentContent');
const charCount = document.getElementById('charCount');
const submitCommentBtn = document.getElementById('submitCommentBtn');
const commentLoggedInInfo = document.getElementById('commentLoggedInInfo');
const commentLoginPrompt = document.getElementById('commentLoginPrompt');
const loginToCommentBtn = document.getElementById('loginToCommentBtn');
const registerToCommentBtn = document.getElementById('registerToCommentBtn');
const replyBtns = document.querySelectorAll('.reply-btn');
const cancelReplyBtns = document.querySelectorAll('.cancel-reply-btn');
const successToast = document.getElementById('successToast');
const errorToast = document.getElementById('errorToast');
const successMessage = document.getElementById('successMessage');
const errorMessage = document.getElementById('errorMessage');
const commentsList = document.getElementById('commentsList');
const loadMoreComments = document.getElementById('loadMoreComments');

// 切换密码可见性
toggleLoginPassword.addEventListener('click', () => {
  const type = loginPassword.getAttribute('type') === 'password' ? 'text' : 'password';
  loginPassword.setAttribute('type', type);
  toggleLoginPassword.querySelector('i').classList.toggle('fa-eye');
  toggleLoginPassword.querySelector('i').classList.toggle('fa-eye-slash');
});

toggleRegisterPassword.addEventListener('click', () => {
  const type = registerPassword.getAttribute('type') === 'password' ? 'text' : 'password';
  registerPassword.setAttribute('type', type);
  toggleRegisterPassword.querySelector('i').classList.toggle('fa-eye');
  toggleRegisterPassword.querySelector('i').classList.toggle('fa-eye-slash');
});

toggleRegisterConfirmPassword.addEventListener('click', () => {
  const type = registerConfirmPassword.getAttribute('type') === 'password' ? 'text' : 'password';
  registerConfirmPassword.setAttribute('type', type);
  toggleRegisterConfirmPassword.querySelector('i').classList.toggle('fa-eye');
  toggleRegisterConfirmPassword.querySelector('i').classList.toggle('fa-eye-slash');
});

// 登录表单验证
loginForm.addEventListener('submit', (e) => {
  e.preventDefault();
  let isValid = true;
  
  if (!loginUsername.value.trim()) {
    loginUsernameError.textContent = '请输入用户名或邮箱';
    loginUsernameError.classList.remove('hidden');
    isValid = false;
  } else {
    loginUsernameError.classList.add('hidden');
  }
  
  if (!loginPassword.value.trim()) {
    loginPasswordError.textContent = '请输入密码';
    loginPasswordError.classList.remove('hidden');
    isValid = false;
  } else {
    loginPasswordError.classList.add('hidden');
  }
  
  if (isValid) {
    // 模拟登录请求
    simulateRequest('/api/login', {
      username: loginUsername.value,
      password: loginPassword.value
    })
    .then(response => {
      showSuccessToast('登录成功！');
      loginModal.classList.add('hidden');
      loginForm.reset();
      // 显示已登录状态
      commentLoggedInInfo.classList.remove('hidden');
      commentLoginPrompt.classList.add('hidden');
    })
    .catch(error => {
      showErrorToast(error.message || '登录失败，请重试');
    });
  }
});

// 注册表单验证
registerForm.addEventListener('submit', (e) => {
  e.preventDefault();
  let isValid = true;
  
  // 用户名验证
  const usernameRegex = /^[a-zA-Z0-9]{3,20}$/;
  if (!registerUsername.value.trim()) {
    registerUsernameError.textContent = '请输入用户名';
    registerUsernameError.classList.remove('hidden');
    isValid = false;
  } else if (!usernameRegex.test(registerUsername.value.trim())) {
    registerUsernameError.textContent = '用户名长度应为3-20个字符，只能包含字母和数字';
    registerUsernameError.classList.remove('hidden');
    isValid = false;
  } else {
    registerUsernameError.classList.add('hidden');
  }
  
  // 邮箱验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!registerEmail.value.trim()) {
    registerEmailError.textContent = '请输入邮箱';
    registerEmailError.classList.remove('hidden');
    isValid = false;
  } else if (!emailRegex.test(registerEmail.value.trim())) {
    registerEmailError.textContent = '请输入有效的邮箱地址';
    registerEmailError.classList.remove('hidden');
    isValid = false;
  } else {
    registerEmailError.classList.add('hidden');
  }
  
  // 密码验证
  const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/;
  if (!registerPassword.value.trim()) {
    registerPasswordError.textContent = '请输入密码';
    registerPasswordError.classList.remove('hidden');
    isValid = false;
  } else if (!passwordRegex.test(registerPassword.value.trim())) {
    registerPasswordError.textContent = '密码长度应为8-20个字符，包含字母和数字';
    registerPasswordError.classList.remove('hidden');
    isValid = false;
  } else {
    registerPasswordError.classList.add('hidden');
  }
  
  // 确认密码验证
  if (!registerConfirmPassword.value.trim()) {
    registerConfirmPasswordError.textContent = '请确认密码';
    registerConfirmPasswordError.classList.remove('hidden');
    isValid = false;
  } else if (registerConfirmPassword.value.trim() !== registerPassword.value.trim()) {
    registerConfirmPasswordError.textContent = '两次输入的密码不一致';
    registerConfirmPasswordError.classList.remove('hidden');
    isValid = false;
  } else {
    registerConfirmPasswordError.classList.add('hidden');
  }
  
  // 同意条款验证
  if (!agreeTerms.checked) {
    agreeTermsError.classList.remove('hidden');
    isValid = false;
  } else {
    agreeTermsError.classList.add('hidden');
  }
  
  if (isValid) {
    // 模拟注册请求
    simulateRequest('/api/register', {
      username: registerUsername.value,
      email: registerEmail.value,
      password: registerPassword.value
    })
    .then(response => {
      showSuccessToast('注册成功！请登录');
      registerModal.classList.add('hidden');
      registerForm.reset();
      agreeTermsError.classList.add('hidden');
      loginModal.classList.remove('hidden');
    })
    .catch(error => {
      showErrorToast(error.message || '注册失败，请重试');
    });
  }
});

// 评论内容字数统计
commentContent.addEventListener('input', () => {
  const length = commentContent.value.length;
  charCount.textContent = length;
  
  if (length > 0 && length <= 500) {
    submitCommentBtn.disabled = false;
    submitCommentBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  } else {
    submitCommentBtn.disabled = true;
    submitCommentBtn.classList.add('opacity-50', 'cursor-not-allowed');
  }
  
  if (length > 500) {
    charCount.classList.add('text-red-500');
  } else {
    charCount.classList.remove('text-red-500');
  }
});

// 评论表单提交
commentForm.addEventListener('submit', (e) => {
  e.preventDefault();
  
  if (!commentContent.value.trim()) {
    showErrorToast('评论内容不能为空');
    return;
  }
  
  if (commentContent.value.length > 500) {
    showErrorToast('评论内容不能超过500个字符');
    return;
  }
  
  // 模拟评论提交
  simulateRequest('/api/comments', {
    content: commentContent.value
  })
  .then(response => {
    showSuccessToast('评论提交成功！');
    
    // 创建新评论元素
    const newComment = document.createElement('div');
    newComment.className = 'comment-item';
    newComment.innerHTML = `
      <div class="flex space-x-4">
        <img src="https://picsum.photos/40/40?random=201" alt="评论用户头像" class="w-12 h-12 rounded-full flex-shrink-0">
        <div class="flex-1">
          <div class="flex items-center justify-between mb-1">
            <h4 class="font-medium">用户123456</h4>
            <span class="text-sm text-gray-500">刚刚</span>
          </div>
          <p class="text-gray-700 mb-2">${escapeHTML(commentContent.value)}</p>
          <div class="flex items-center space-x-4 text-sm">
            <button class="flex items-center space-x-1 text-gray-500 hover:text-primary transition-colors">
              <i class="fa fa-thumbs-up"></i>
              <span>0</span>
            </button>
            <button class="reply-btn flex items-center space-x-1 text-gray-500 hover:text-primary transition-colors">
              <i class="fa fa-reply"></i>
              <span>回复</span>
            </button>
          </div>
        </div>
      </div>
    `;
    
    // 将新评论添加到评论列表顶部
    const firstComment = commentsList.querySelector('.comment-item');
    if (firstComment) {
      commentsList.insertBefore(newComment, firstComment);
    } else {
      commentsList.appendChild(newComment);
    }
    
    // 清空评论框
    commentContent.value = '';
    charCount.textContent = '0';
    submitCommentBtn.disabled = true;
    submitCommentBtn.classList.add('opacity-50', 'cursor-not-allowed');
    
    // 重新绑定回复按钮事件
    bindReplyButtons();
  })
  .catch(error => {
    showErrorToast(error.message || '评论提交失败，请重试');
  });
});

// 登录/注册以评论
loginToCommentBtn.addEventListener('click', () => {
  loginModal.classList.remove('hidden');
  registerModal.classList.add('hidden');
});

registerToCommentBtn.addEventListener('click', () => {
  registerModal.classList.remove('hidden');
  loginModal.classList.add('hidden');
});

// 回复按钮事件绑定
function bindReplyButtons() {
  const replyBtns = document.querySelectorAll('.reply-btn');
  const cancelReplyBtns = document.querySelectorAll('.cancel-reply-btn');
  
  replyBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      const commentItem = this.closest('.comment-item');
      const replyForm = commentItem.querySelector('.reply-form-container');
      
      if (replyForm) {
        replyForm.classList.toggle('hidden');
      } else {
        // 如果没有回复表单，创建一个
        const replyFormHtml = `
          <div class="reply-form-container mt-3">
            <form class="space-y-2">
              <textarea rows="2" placeholder="回复..." class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary resize-none text-sm"></textarea>
              <div class="flex justify-end">
                <button type="button" class="cancel-reply-btn px-3 py-1 mr-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors text-sm">
                  取消
                </button>
                <button type="submit" class="px-3 py-1 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm">
                  回复
                </button>
              </div>
            </form>
          </div>
        `;
        
        this.parentNode.insertAdjacentHTML('afterend', replyFormHtml);
        
        // 绑定新添加的取消回复按钮
        const newCancelBtn = this.parentNode.nextElementSibling.querySelector('.cancel-reply-btn');
        newCancelBtn.addEventListener('click', function() {
          this.closest('.reply-form-container').remove();
        });
        
        // 绑定新添加的回复表单提交事件
        const newReplyForm = this.parentNode.nextElementSibling.querySelector('form');
        newReplyForm.addEventListener('submit', function(e) {
          e.preventDefault();
          const replyContent = this.querySelector('textarea').value.trim();
          
          if (!replyContent) {
            showErrorToast('回复内容不能为空');
            return;
          }
          
          // 模拟回复提交
          simulateRequest(`/api/comments/${commentId}/replies`, {
            content: replyContent
          })
          .then(response => {
            showSuccessToast('回复提交成功！');
            
            // 获取评论项
            const commentItem = this.closest('.comment-item');
            const repliesContainer = commentItem.querySelector('.replies-container');
            
            // 如果没有回复容器，创建一个
            if (!repliesContainer) {
              const repliesHtml = `
                <div class="replies-container mt-4 pl-4 border-l-2 border-gray-100 space-y-4">
                  <!-- 回复将被添加到这里 -->
                </div>
              `;
              commentItem.querySelector('.flex-1').appendChild(document.createRange().createContextualFragment(repliesHtml));
            }
            
            // 创建新回复
            const newReply = document.createElement('div');
            newReply.className = 'reply-item';
            newReply.innerHTML = `
              <div class="flex space-x-3">
                <img src="https://picsum.photos/40/40?random=201" alt="回复用户头像" class="w-8 h-8 rounded-full flex-shrink-0">
                <div class="flex-1">
                  <div class="flex items-center justify-between mb-1">
                    <h5 class="font-medium text-sm">用户123456</h5>
                    <span class="text-xs text-gray-500">刚刚</span>
                  </div>
                  <p class="text-gray-700 text-sm mb-1">${escapeHTML(replyContent)}</p>
                  <div class="flex items-center space-x-3 text-xs">
                    <button class="flex items-center space-x-1 text-gray-500 hover:text-primary transition-colors">
                      <i class="fa fa-thumbs-up"></i>
                      <span>0</span>
                    </button>
                    <button class="reply-btn flex items-center space-x-1 text-gray-500 hover:text-primary transition-colors">
                      <i class="fa fa-reply"></i>
                      <span>回复</span>
                    </button>
                  </div>
                </div>
              </div>
            `;
            
            // 添加新回复
            const repliesContainer = commentItem.querySelector('.replies-container');
            repliesContainer.appendChild(newReply);
            
            // 移除回复表单
            this.closest('.reply-form-container').remove();
            
            // 重新绑定回复按钮事件
            bindReplyButtons();
          })
          .catch(error => {
            showErrorToast(error.message || '回复提交失败，请重试');
          });
        });
      }
    });
  });
  
  cancelReplyBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      this.closest('.reply-form-container').remove();
    });
  });
}

// 初始绑定回复按钮
bindReplyButtons();

// 加载更多评论
loadMoreComments.addEventListener('click', () => {
  // 模拟加载更多评论
  loadMoreComments.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>加载中...';
  
  simulateRequest('/api/comments?page=2')
  .then(response => {
    showSuccessToast('已加载全部评论');
    loadMoreComments.innerHTML = '已显示全部评论';
    loadMoreComments.disabled = true;
    loadMoreComments.classList.add('opacity-50', 'cursor-not-allowed');
  })
  .catch(error => {
    showErrorToast(error.message || '加载评论失败，请重试');
    loadMoreComments.innerHTML = '加载更多评论';
  });
});

// 显示成功提示
function showSuccessToast(message) {
  successMessage.textContent = message;
  successToast.classList.remove('translate-y-20', 'opacity-0');
  
  setTimeout(() => {
    successToast.classList.add('translate-y-20', 'opacity-0');
  }, 3000);
}

// 显示错误提示
function showErrorToast(message) {
  errorMessage.textContent = message;
  errorToast.classList.remove('translate-y-20', 'opacity-0');
  
  setTimeout(() => {
    errorToast.classList.add('translate-y-20', 'opacity-0');
  }, 3000);
}

// 转义HTML特殊字符
function escapeHTML(str) {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}

// 模拟API请求
function simulateRequest(url, data = null) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 模拟20%的失败概率
      if (Math.random() < 0.2) {
        reject({ message: '请求失败，请重试' });
        return;
      }
      
      // 模拟成功响应
      resolve({ 
        success: true,
        data: { id: Math.floor(Math.random() * 10000) } 
      });
    }, 1000);
  });
}    